package common.Forum;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;

import type.TaskDescriptions;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.PixelFormat;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.project.institute.DAO.InstituteListFragmentDAO;
import com.project.trac.R;

import core.modules.DatabaseConnector;

public class ViewReplies extends InstituteListFragmentDAO implements TaskDescriptions {
	
	private View parent;
	private TextView spiel;
	private EditText textBox;
	private Dialog dialog;
	private AlertDialog.Builder alertDialog;
	
	private int USER_ID;
	private int forumID;
	
	public static ListFragment newInstance(Context context) {
		ViewReplies lf = new ViewReplies();
		return lf;
	}

	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		
		return (ViewGroup) inflater.inflate(R.layout.generic_list, null);
	}

	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		
		OnItemClickListener click = new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> av, View view, int position, long id) {
				
				String item = av.getItemAtPosition(position).toString().replace("=", "");
				USER_ID = Integer.valueOf(item.substring(item.indexOf("userId")+6, item.indexOf("}")));
				forumID = Integer.valueOf(item.substring(item.indexOf("forum_id")+8, item.indexOf(", userId")));
				
				registerForContextMenu(av);
				getActivity().openContextMenu(av);
			}
			
		};

		getListView().setOnItemClickListener(click);

	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {

		if (getUserID() == USER_ID) 
			menu.add(Menu.NONE, Menu.FIRST + 3, Menu.NONE, "Delete thread");
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		
		switch (item.getItemId()) {

		case Menu.FIRST + 3:
			deleteReply();
			break;
		}
		
		return super.onContextItemSelected(item);
	}
	
	public void onResume() {
		new AsynchronousTask().execute(INITIALIZE);
		super.onResume();
	}

	public void onBackPressed() {
		super.getActivity().onBackPressed();
	}
	
	public void onAttachedToWindow() {
		super.getActivity().onAttachedToWindow();
		Window window = getActivity().getWindow();
		window.setFormat(PixelFormat.RGBA_8888);
	}
	
	void deleteReply() {
		
		parent = View.inflate(getActivity(), R.layout.generic_dialog_box, null);
		alertDialog = new AlertDialog.Builder(getActivity());
	    alertDialog.setCancelable(false);
	    
		textBox = (EditText) parent.findViewById(R.id.et_dialog_input);
		spiel = (TextView) parent.findViewById(R.id.tv_dialog_spiel);
		spiel.setVisibility(View.GONE);
		textBox.setVisibility(View.GONE);
		
		alertDialog.setPositiveButton("Delete", new DialogInterface.OnClickListener(){
				@Override
				public void onClick(DialogInterface dialog, int which) {
					new AsynchronousTask().execute(DROP);
					Toast.makeText(getActivity().getApplicationContext(), "reply deleted", Toast.LENGTH_SHORT).show();
					((ViewGroup) parent.getParent()).removeView(parent);
					dialog.dismiss();
			}
		});
		
		alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){
				@Override
				public void onClick(DialogInterface dialog, int which) {
					((ViewGroup) parent.getParent()).removeView(parent);
					dialog.dismiss();
				}
		});
		
		
		dialog = alertDialog.setTitle("Really delete #" + forumID + "?").setView(parent).create();
		dialog.show();
	}
	
	private class AsynchronousTask extends AsyncTask<String, String, String> {

		HashMap<String, String> m;
		ArrayList<HashMap<String, String>> arrayList = new ArrayList<HashMap<String, String>>();

		ListAdapter listAdapter;

		String KEY_PERSON = "person";
		String KEY_DATE_REPLIED = "date";
		String KEY_CONTENT = "content";
		String KEY_FORUM_ID = "forum_id";
		String KEY_USER_ID = "userId"; 
		
		protected void onPreExecute() {
			super.onPreExecute();
		}

		protected String doInBackground(String... args) {

			try {

				if (args[0].equalsIgnoreCase(INITIALIZE)) {
					ResultSet rs = DatabaseConnector.getStatement().executeQuery(
							"SELECT b.id, b.replyto_id AS rid, DATE_FORMAT(b.replyto_date, '%Y-%b-%d') AS 'replyto_date', b.uid,"
							+ " CONCAT("
							+ " (SELECT "
							+ " 	CASE"
							+ " 		WHEN title IS NULL THEN ''"
							+ " 		WHEN title IS NOT NULL THEN title"
							+ " 	END as title"
							+ " FROM users"
							+ " WHERE users.id = b.uid), ' ', users.firstname, ' ', users.lastname) AS user, b.content"
							+ " FROM forum AS a, forum AS b"
							+ " JOIN users ON users.id = b.uid"
							+ " WHERE b.replyto_id = a.id AND b.isThread = 3 AND b.section IS NOT NULL");

					while (rs.next()) {
						m = new HashMap<String, String>();
						m.put(KEY_PERSON, rs.getString("user"));
						m.put(KEY_DATE_REPLIED,  rs.getString("replyto_date"));
						m.put(KEY_CONTENT, rs.getString("b.content"));
						m.put(KEY_FORUM_ID, rs.getString("b.id"));
						m.put(KEY_USER_ID, rs.getString("b.uid"));
						arrayList.add(m);
					}
				}
				
				if (args[0].equalsIgnoreCase(DROP)) {
					DatabaseConnector.getConnection().setAutoCommit(false);
					PreparedStatement id = DatabaseConnector.getConnection().prepareStatement("DELETE FROM forum WHERE id = ? AND isThread = 3");
					id.setInt(1, forumID);		id.executeUpdate(); 	id.close();

					getActivity().runOnUiThread(new Runnable() {

						@Override
						public void run() {
							getActivity().startActivity(getActivity().getIntent());
							getActivity().finish();
						}
					});
					
				}
				
			} catch (SQLException e) {
				DatabaseConnector.Logger(getClass(), "doInBackground", e);
			}

			return null;
		}

		protected void onPostExecute(String postExecute) {
			getActivity().runOnUiThread(new Runnable() {

				@Override
				public void run() {

					listAdapter = new SimpleAdapter(getActivity(), arrayList, R.layout.common_forum_replies_detail, 
							new String[] {KEY_FORUM_ID, KEY_PERSON, KEY_DATE_REPLIED, KEY_CONTENT, KEY_USER_ID}, 
							new int[] {R.id.tv_forumId, R.id.tv_key_person, R.id.tv_date_replied, R.id.tv_content});

					setListAdapter(listAdapter);
				}
			});
		}
	}
}